package com.kgc.web.listener; /**
 * <h3>项目名称:demo03050</h3>
 * <p>本API描述:${description}</p>
 * <p>@author : AliyZhang</p>
 * <p>@date : 2021-03-08 13:05</p>
 **/

import com.kgc.entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
/*该监听器对象由程序员创建
* 监听某个会话里的某个数据的变化
*/
@WebListener
public class MyOnlineListener implements HttpSessionBindingListener {
    //让监听器对象绑定会话里的数据
    private User user;

    public MyOnlineListener() {
    }

    public MyOnlineListener(User user) {
        this.user = user;
    }

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        /*该方法一旦被调用，意味着有用户添加到session里,
        就让网站里的在线人数+1*/

        //获取网站应用对象
        ServletContext application = event.getSession().getServletContext();
        //从网站应用对象中获取总的在线人数
        Object totalOnline = application.getAttribute("totalOnline");
        //判断是否首次访问网站
        if(totalOnline==null){
            application.setAttribute("totalOnline",1);
        }else{
            application.setAttribute("totalOnline",((int)totalOnline)+1);
        }
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        ServletContext application = event.getSession().getServletContext();
        Object totalOnline = application.getAttribute("totalOnline");
        application.setAttribute("totalOnline",((int)totalOnline)-1);
    }
}
